﻿#pragma once
#include "constants.h"
#include "draw_utils.h"
#include "tetris_block.h"
#include "block_data.h"
#include "ai_decision.h"
#include <graphics.h>
#include <iostream>
#include <ctime>
#include <queue>



// ======================
// 模式选择界面实现
// ======================
inline GameMode ShowModeSelection()
{
    // 确保是单倍宽度窗口
    if (getwidth() != SCREEN_WIDTH) {
        closegraph();
        initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    // 加载背景图片
    IMAGE startBg;
    bool hasBackground = false;

    // 改进的图片加载判断方式
    try {
        loadimage(&startBg, _T("./resources/startbg.jpg"), SCREEN_WIDTH, SCREEN_HEIGHT, true);
        // 通过检查图片尺寸判断是否加载成功
        if (startBg.getwidth() > 0 && startBg.getheight() > 0) {
            hasBackground = true;
        }
    }
    catch (...) {
        hasBackground = false;
    }

    // 当前选中模式
    int selectedMode = 0;
    bool confirmed = false;

    while (!confirmed) {
        // 开始双缓冲绘制
        BeginBatchDraw();

        // 绘制背景
        if (hasBackground) {
            putimage(0, 0, &startBg);
        }
        else {
            // 使用渐变背景替代
            for (int y = 0; y < SCREEN_HEIGHT; y++) {
                float ratio = (float)y / SCREEN_HEIGHT;
                COLORREF color = hsvToRgb(220, 0.7f, 0.3f + ratio * 0.5f);
                setlinecolor(color);
                line(0, y, SCREEN_WIDTH, y);
            }
        }

        // 绘制标题（更醒目的大字）
        settextstyle(50, 0, _T("微软雅黑"), 0, 0, 1000, false, false, false);
        settextcolor(hsvToRgb(60, 1.0f, 1.0f)); // 亮黄色
        setbkmode(TRANSPARENT); // 透明背景

        // 标题文字描边效果
        settextstyle(50, 0, _T("微软雅黑"), 0, 0, 1000, false, false, false);
        settextcolor(BLACK);
        for (int offset = -2; offset <= 2; offset++) {
            outtextxy(SCREEN_WIDTH / 2 - 120 + offset, 30, _T("选择游戏模式"));
            outtextxy(SCREEN_WIDTH / 2 - 120, 30 + offset, _T("选择游戏模式"));
        }
        settextcolor(hsvToRgb(60, 1.0f, 1.0f)); // 恢复亮黄色
        outtextxy(SCREEN_WIDTH / 2 - 120, 30, _T("选择游戏模式"));

        // 绘制模式选项
        settextstyle(36, 0, _T("微软雅黑"), 0, 0, 900, false, false, false);

        for (int i = 0; i < MODE_COUNT; i++) {
            // 选中模式高亮显示
            if (i == selectedMode) {
                // 选中项背景高亮
                setfillcolor(hsvToRgb(30, 0.3f, 0.9f)); // 浅橙色
                solidroundrect(SCREEN_WIDTH / 2 - 120, 150 + i * 80 - 5,
                    SCREEN_WIDTH / 2 + 120, 150 + i * 80 + 50, 10, 10);

                // 选中项文字效果
                settextcolor(hsvToRgb(0, 1.0f, 1.0f)); // 红色

                //// 文字描边
                //settextcolor(BLACK);
                //for (int offset = -1; offset <= 1; offset++) {
                //    outtextxy(SCREEN_WIDTH / 2 - 100 + offset, 150 + i * 80, _T("> "));
                //    outtextxy(SCREEN_WIDTH / 2 - 70 + offset, 150 + i * 80, MODE_NAMES[i]);
                //}
                settextcolor(hsvToRgb(0, 1.0f, 1.0f)); // 红色
            }
            else {
                settextcolor(hsvToRgb(120, 0.8f, 0.9f)); // 浅绿色
            }

            outtextxy(SCREEN_WIDTH / 2 - 100, 150 + i * 80, _T("  ")); // 占位对齐
            outtextxy(SCREEN_WIDTH / 2 - 70, 150 + i * 80, MODE_NAMES[i]);
        }

        // 绘制操作提示（更醒目的提示）
        settextstyle(24, 0, _T("微软雅黑"), 0, 0, 800, false, false, false);
        settextcolor(WHITE);

        settextcolor(BROWN);
        outtextxy(SCREEN_WIDTH / 2 - 120, 600, _T("方向键上下选择，回车键确认"));

        // 结束双缓冲绘制
        FlushBatchDraw();

        // 处理键盘输入
        if (GetAsyncKeyState(VK_UP) & 0x8000) {
            selectedMode = (selectedMode - 1 + MODE_COUNT) % MODE_COUNT;
            Sleep(150); // 防止按键过快
        }
        else if (GetAsyncKeyState(VK_DOWN) & 0x8000) {
            selectedMode = (selectedMode + 1) % MODE_COUNT;
            Sleep(150);
        }
        else if (GetAsyncKeyState(VK_RETURN) & 0x8000) {
            confirmed = true;

            // 添加确认动画效果
            for (int alpha = 0; alpha <= 255; alpha += 15) {
                BeginBatchDraw();
                if (hasBackground) {
                    putimage(0, 0, &startBg);
                }

                // 绘制选中项高亮
                setfillcolor(hsvToRgb(30, 0.3f, 0.9f));
                solidroundrect(SCREEN_WIDTH / 2 - 120, 150 + selectedMode * 80 - 5,
                    SCREEN_WIDTH / 2 + 120, 150 + selectedMode * 80 + 50, 10, 10);

                // 绘制对勾动画
                settextstyle(36, 0, _T("微软雅黑"));
                settextcolor(hsvToRgb(120, 0.9f, 0.9f));
                outtextxy(SCREEN_WIDTH / 2 - 100, 150 + selectedMode * 80, _T("✓"));
                outtextxy(SCREEN_WIDTH / 2 - 70, 150 + selectedMode * 80, MODE_NAMES[selectedMode]);

                FlushBatchDraw();
                Sleep(20);
            }
            Sleep(500); // 显示确认标记
        }

        Sleep(50); // 降低CPU占用
    }

    return static_cast<GameMode>(selectedMode);
}

// ======================
// 询问是否继续游戏界面实现
// ======================
inline bool AskToContinue()
{
    // 确保是单倍宽度窗口
    if (getwidth() != SCREEN_WIDTH) {
        closegraph();
        initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    // 加载背景图片
    IMAGE startBg;
    bool hasBackground = false;

    try {
        loadimage(&startBg, _T("./resources/startbg.jpg"), SCREEN_WIDTH, SCREEN_HEIGHT, true);
        if (startBg.getwidth() > 0 && startBg.getheight() > 0) {
            hasBackground = true;
        }
    }
    catch (...) {
        hasBackground = false;
    }

    bool selectedYes = true; // 默认选中"是"
    bool confirmed = false;

    while (!confirmed) {
        // 开始双缓冲绘制
        BeginBatchDraw();

        // 绘制背景
        if (hasBackground) {
            putimage(0, 0, &startBg);
        }
        else {
            // 渐变背景
            for (int y = 0; y < SCREEN_HEIGHT; y++) {
                float ratio = (float)y / SCREEN_HEIGHT;
                setlinecolor(hsvToRgb(220, 0.7f, 0.3f + ratio * 0.5f));
                line(0, y, SCREEN_WIDTH, y);
            }
        }

        // 绘制标题
        settextstyle(50, 0, _T("微软雅黑"), 0, 0, 1000, false, false, false);
        settextcolor(hsvToRgb(60, 1.0f, 1.0f)); // 亮黄色
        setbkmode(TRANSPARENT);

        // 标题描边效果
        settextcolor(BLACK);
        for (int offset = -2; offset <= 2; offset++) {
            outtextxy(SCREEN_WIDTH / 2 - 150 + offset, 50, _T("游戏结束,是否继续？"));
            outtextxy(SCREEN_WIDTH / 2 - 150, 50 + offset, _T("游戏结束,是否继续？"));
        }
        settextcolor(hsvToRgb(60, 1.0f, 1.0f));
        outtextxy(SCREEN_WIDTH / 2 - 150, 50, _T("游戏结束,是否继续？"));

        // 绘制选项
        settextstyle(36, 0, _T("微软雅黑"), 0, 0, 900, false, false, false);

        // "是"选项
        if (selectedYes) {
            setfillcolor(hsvToRgb(30, 0.3f, 0.9f));
            solidroundrect(SCREEN_WIDTH / 2 - 150, 180, SCREEN_WIDTH / 2 - 20, 250, 10, 10);

            settextcolor(hsvToRgb(0, 1.0f, 1.0f));
            //settextcolor(BLACK);
            //for (int offset = -1; offset <= 1; offset++) {
            //    outtextxy(SCREEN_WIDTH / 2 - 120 + offset, 200, _T("是"));
            //}
            settextcolor(hsvToRgb(0, 1.0f, 1.0f));
        }
        else {
            settextcolor(hsvToRgb(120, 0.8f, 0.9f));
        }
        outtextxy(SCREEN_WIDTH / 2 - 120, 200, _T("是"));

        // "否"选项
        if (!selectedYes) {
            setfillcolor(hsvToRgb(30, 0.3f, 0.9f));
            solidroundrect(SCREEN_WIDTH / 2 + 20, 180, SCREEN_WIDTH / 2 + 150, 250, 10, 10);

            settextcolor(hsvToRgb(0, 1.0f, 1.0f));
            //settextcolor(BLACK);
            //for (int offset = -1; offset <= 1; offset++) {
            //    outtextxy(SCREEN_WIDTH / 2 + 50 + offset, 200, _T("否"));
            //}
            settextcolor(hsvToRgb(0, 1.0f, 1.0f));
        }
        else {
            settextcolor(hsvToRgb(120, 0.8f, 0.9f));
        }
        outtextxy(SCREEN_WIDTH / 2 + 50, 200, _T("否"));

        // 绘制操作提示
        settextstyle(24, 0, _T("微软雅黑"), 0, 0, 800, false, false, false);

        settextcolor(BROWN);
        outtextxy(SCREEN_WIDTH / 2 - 120, 300, _T("方向键左右选择，回车键确认"));

        // 结束双缓冲绘制
        FlushBatchDraw();

        // 处理键盘输入
        if (GetAsyncKeyState(VK_LEFT) & 0x8000) {
            selectedYes = true;
            Sleep(150);
        }
        else if (GetAsyncKeyState(VK_RIGHT) & 0x8000) {
            selectedYes = false;
            Sleep(150);
        }
        else if (GetAsyncKeyState(VK_RETURN) & 0x8000) {
            confirmed = true;

            // 确认动画
            for (int alpha = 0; alpha <= 255; alpha += 15) {
                BeginBatchDraw();
                if (hasBackground) {
                    putimage(0, 0, &startBg);
                }

                if (selectedYes) {
                    setfillcolor(hsvToRgb(30, 0.3f, 0.9f));
                    solidroundrect(SCREEN_WIDTH / 2 - 150, 180, SCREEN_WIDTH / 2 - 20, 250, 10, 10);

                    settextcolor(hsvToRgb(120, 0.9f, 0.9f));
                    outtextxy(SCREEN_WIDTH / 2 - 120, 200, _T("✓"));
                }
                else {
                    setfillcolor(hsvToRgb(30, 0.3f, 0.9f));
                    solidroundrect(SCREEN_WIDTH / 2 + 20, 180, SCREEN_WIDTH / 2 + 150, 250, 10, 10);

                    settextcolor(hsvToRgb(120, 0.9f, 0.9f));
                    outtextxy(SCREEN_WIDTH / 2 + 50, 200, _T("✓"));
                }

                FlushBatchDraw();
                Sleep(20);
            }
            Sleep(500);
        }

        Sleep(50);
    }

    return selectedYes;
}

// ======================
// 单人游戏实现
// ======================
inline void RunSinglePlayerGame()
{
    // 初始化随机种子
    unsigned int seed = static_cast<unsigned>(time(nullptr));

    // 初始化方块池（足够大，比如1000个）
    BlockPool blockPool;
    blockPool.Initialize(seed, 1000);

    // 创建双缓冲图像
    IMAGE bufferImg(SCREEN_WIDTH, SCREEN_HEIGHT);

    // 设置背景颜色为白色
    setbkcolor(WHITE);
    cleardevice();

    // 加载背景图片
    LoadBackground();

    // 初始化分数管理器
    ScoreManager scoreManager;

    // 绘制游戏区域
    GameArea gameArea(scoreManager);
    PreviewArea previewArea;

    // 初始化当前方块和下一个方块的索引
    int curBlockIndex = 0;       // 当前方块的索引
    int nextBlockIndex = 1;      // 下一个方块的索引

    // 获取当前方块和下一个方块
    TetrisBlock currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 0);
    TetrisBlock nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
    previewArea.UpdateNextBlock(nextBlock);

    // 游戏主循环
    while (true) {
        // 开始双缓冲绘制
        BeginBatchDraw();

        // 1. 清空缓冲图像并绘制背景
        cleardevice();
        LoadBackground();  // 现在会绘制到缓冲图像

        // 2. 在缓冲图像上绘制游戏区域
        gameArea.Draw();
        gameArea.DrawTitle(L"Player");

        // 3. 在缓冲图像上绘制当前方块
        currentBlock.Draw(MARGIN, MARGIN);

        // 4. 在缓冲图像上绘制预览框
        previewArea.Draw();

        // 5. 在缓冲图像上绘制分数和等级
        scoreManager.Draw();

        // 结束双缓冲绘制，一次性刷新到屏幕
        FlushBatchDraw();

        // 检查暂停键
        if (GetAsyncKeyState(VK_SPACE) & 0x8000) {
            // 暂停游戏
            MessageBox(nullptr, _T("游戏已暂停\n\n按确定继续游戏"), _T("暂停"), MB_OK);

            // 防止按键持续检测
            while (GetAsyncKeyState(VK_SPACE) & 0x8000) {
                Sleep(100);
            }
        }

        // 处理用户输入
        if (GetAsyncKeyState('A') & 0x8000 || GetAsyncKeyState(VK_LEFT) & 0x8000) { // 左移
            if (gameArea.CanMoveLeft(currentBlock)) {
                currentBlock.MoveLeft();
            }
        }
        if (GetAsyncKeyState('D') & 0x8000 || GetAsyncKeyState(VK_RIGHT) & 0x8000) { // 右移
            if (gameArea.CanMoveRight(currentBlock)) {
                currentBlock.MoveRight();
            }
        }
        if (GetAsyncKeyState('S') & 0x8000 || GetAsyncKeyState(VK_DOWN) & 0x8000) { // 下移
            if (gameArea.CanMoveDown(currentBlock)) {
                currentBlock.MoveDown();
            }
        }
        if (GetAsyncKeyState('W') & 0x8000 || GetAsyncKeyState(VK_UP) & 0x8000) { // 旋转
            if (gameArea.CanRotate(currentBlock)) {
                currentBlock.Rotate();
            }
        }

        // 方块自动下落逻辑
        if (gameArea.CanMoveDown(currentBlock)) {
            currentBlock.MoveDown(); // 下移一格
        }
        else {
            // 固定当前方块
            gameArea.FixBlock(currentBlock);

            // 更新索引
            curBlockIndex = nextBlockIndex;
            nextBlockIndex += 1;

            // 检查游戏结束
            if (!gameArea.CanMoveDown(currentBlock) && currentBlock.GetY() == 0) {
                // 游戏结束提示
                settextstyle(40, 0, _T("黑体"));
                settextcolor(RED);
                outtextxy(SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("游戏结束!"));
                FlushBatchDraw(); // 确保结束文字显示
                Sleep(2000);
                break;
            }
            else {
                // 获取新方块
                currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 0);
                nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
                previewArea.UpdateNextBlock(nextBlock);
            }
        }

        // 根据等级调整下落速度
        int higherLevel = scoreManager.GetLevel(); // 单人模式只有一个玩家，直接使用当前玩家的等级
        int delay = 150 - (higherLevel - 1) * 20; // 每升一级减少 20 毫秒
        if (delay < 50) delay = 50; // 最小延迟为 50 毫秒
        Sleep(delay);
    }
}


// ======================
// 双人游戏实现
// ======================
inline void RunTwoPlayerGame()
{
    // 初始化随机种子
    unsigned int seed = static_cast<unsigned>(time(nullptr));

    // 初始化共享方块池
    BlockPool blockPool;
    blockPool.Initialize(seed, 1000);

    // 初始化图形窗口(双倍宽度)
    initgraph(TWO_PLAYER_SCREEN_WIDTH, SCREEN_HEIGHT);

    // 设置背景颜色为白色
    setbkcolor(WHITE);
    cleardevice();

    // 加载并拉伸背景图片
    IMAGE background;
    loadimage(&background, _T("./resources/background.jpg"), TWO_PLAYER_SCREEN_WIDTH, SCREEN_HEIGHT, true);
    putimage(0, 0, &background);

    // 初始化分数管理器
    ScoreManager leftScoreManager;
    ScoreManager rightScoreManager(RIGHT_GAME_OFFSET_X + GAME_AREA_WIDTH + MARGIN * 2,
        MARGIN + PREVIEW_HEIGHT * CELL_SIZE + MARGIN);

    // 初始化游戏区域
    GameArea leftGameArea(leftScoreManager);
    GameArea rightGameArea(rightScoreManager);

    // 初始化预览区域
    PreviewArea leftPreviewArea;
    PreviewArea rightPreviewArea(RIGHT_GAME_OFFSET_X + GAME_AREA_WIDTH + MARGIN * 2, MARGIN);

    // 初始化玩家状态
    struct PlayerState {
        bool gameOver = false;
        int blockIndex = 0;       // 当前方块的索引
        int nextBlockIndex = 1;   // 下一个方块的索引
        TetrisBlock currentBlock;
        TetrisBlock nextBlock;
    };

    PlayerState leftPlayer, rightPlayer;

    // 初始化方块(使用共享blockPool)
    leftPlayer.currentBlock = blockPool.GetBlock(leftPlayer.blockIndex, WIDTH / 2 - 2, 0);
    leftPlayer.nextBlock = blockPool.GetBlock(leftPlayer.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
    leftPreviewArea.UpdateNextBlock(leftPlayer.nextBlock);

    rightPlayer.currentBlock = blockPool.GetBlock(rightPlayer.blockIndex, WIDTH / 2 - 2, 0);
    rightPlayer.nextBlock = blockPool.GetBlock(rightPlayer.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
    rightPreviewArea.UpdateNextBlock(rightPlayer.nextBlock);

    // 游戏主循环
    while (true) {
        // 开始双缓冲绘制
        BeginBatchDraw();

        // 清空缓冲图像并绘制背景
        cleardevice();
        putimage(0, 0, &background);

        // 绘制左侧游戏区域
        leftGameArea.Draw(MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        leftGameArea.DrawTitle(L"Player1", MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        if (!leftPlayer.gameOver) {
            leftPlayer.currentBlock.Draw(MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        }
        leftPreviewArea.Draw();
        leftScoreManager.Draw();

        // 绘制右侧游戏区域
        rightGameArea.Draw(MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        rightGameArea.DrawTitle(L"Player2", MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        if (!rightPlayer.gameOver) {
            rightPlayer.currentBlock.Draw(MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        }
        rightPreviewArea.Draw();
        rightScoreManager.Draw();

        // 结束双缓冲绘制
        FlushBatchDraw();

        // 检查暂停键
        if (GetAsyncKeyState(VK_SPACE) & 0x8000) {
            // 暂停游戏
            MessageBox(nullptr, _T("游戏已暂停\n\n按确定继续游戏"), _T("暂停"), MB_OK);

            // 防止按键持续检测
            while (GetAsyncKeyState(VK_SPACE) & 0x8000) {
                Sleep(100);
            }
        }

        // 处理左侧玩家输入(WASD)
        if (!leftPlayer.gameOver) {
            if (GetAsyncKeyState('A') & 0x8000) { // 左移
                if (leftGameArea.CanMoveLeft(leftPlayer.currentBlock)) {
                    leftPlayer.currentBlock.MoveLeft();
                }
            }
            if (GetAsyncKeyState('D') & 0x8000) { // 右移
                if (leftGameArea.CanMoveRight(leftPlayer.currentBlock)) {
                    leftPlayer.currentBlock.MoveRight();
                }
            }
            if (GetAsyncKeyState('S') & 0x8000) { // 下移
                if (leftGameArea.CanMoveDown(leftPlayer.currentBlock)) {
                    leftPlayer.currentBlock.MoveDown();
                }
            }
            if (GetAsyncKeyState('W') & 0x8000) { // 旋转
                if (leftGameArea.CanRotate(leftPlayer.currentBlock)) {
                    leftPlayer.currentBlock.Rotate();
                }
            }
        }

        // 处理右侧玩家输入(方向键)
        if (!rightPlayer.gameOver) {
            if (GetAsyncKeyState(VK_LEFT) & 0x8000) { // 左移
                if (rightGameArea.CanMoveLeft(rightPlayer.currentBlock)) {
                    rightPlayer.currentBlock.MoveLeft();
                }
            }
            if (GetAsyncKeyState(VK_RIGHT) & 0x8000) { // 右移
                if (rightGameArea.CanMoveRight(rightPlayer.currentBlock)) {
                    rightPlayer.currentBlock.MoveRight();
                }
            }
            if (GetAsyncKeyState(VK_DOWN) & 0x8000) { // 下移
                if (rightGameArea.CanMoveDown(rightPlayer.currentBlock)) {
                    rightPlayer.currentBlock.MoveDown();
                }
            }
            if (GetAsyncKeyState(VK_UP) & 0x8000) { // 旋转
                if (rightGameArea.CanRotate(rightPlayer.currentBlock)) {
                    rightPlayer.currentBlock.Rotate();
                }
            }
        }

        // 左侧玩家方块逻辑
        if (!leftPlayer.gameOver) {
            if (leftGameArea.CanMoveDown(leftPlayer.currentBlock)) {
                leftPlayer.currentBlock.MoveDown();
            }
            else {
                leftGameArea.FixBlock(leftPlayer.currentBlock);

                // 更新索引
                leftPlayer.blockIndex = leftPlayer.nextBlockIndex;
                leftPlayer.nextBlockIndex += 1;

                // 检查游戏结束
                if (!leftGameArea.CanMoveDown(leftPlayer.currentBlock) && leftPlayer.currentBlock.GetY() == 0) {
                    leftPlayer.gameOver = true;
                    settextstyle(30, 0, _T("黑体"));
                    settextcolor(RED);
                    outtextxy(LEFT_GAME_OFFSET_X + SCREEN_WIDTH / 2 - 60, SCREEN_HEIGHT / 2, _T("左方结束"));
                    FlushBatchDraw();
                }
                else {
                    // 获取新方块
                    leftPlayer.currentBlock = blockPool.GetBlock(leftPlayer.blockIndex, WIDTH / 2 - 2, 0);
                    leftPlayer.nextBlock = blockPool.GetBlock(leftPlayer.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
                    leftPreviewArea.UpdateNextBlock(leftPlayer.nextBlock);
                }
            }
        }

        // 右侧玩家方块逻辑
        if (!rightPlayer.gameOver) {
            if (rightGameArea.CanMoveDown(rightPlayer.currentBlock)) {
                rightPlayer.currentBlock.MoveDown();
            }
            else {
                rightGameArea.FixBlock(rightPlayer.currentBlock);

                // 更新索引
                rightPlayer.blockIndex = rightPlayer.nextBlockIndex;
                rightPlayer.nextBlockIndex += 1;

                // 检查游戏结束
                if (!rightGameArea.CanMoveDown(rightPlayer.currentBlock) && rightPlayer.currentBlock.GetY() == 0) {
                    rightPlayer.gameOver = true;
                    settextstyle(30, 0, _T("黑体"));
                    settextcolor(RED);
                    outtextxy(RIGHT_GAME_OFFSET_X + SCREEN_WIDTH / 2 - 60, SCREEN_HEIGHT / 2, _T("右方结束"));
                    FlushBatchDraw();
                }
                else {
                    // 获取新方块
                    rightPlayer.currentBlock = blockPool.GetBlock(rightPlayer.blockIndex, WIDTH / 2 - 2, 0);
                    rightPlayer.nextBlock = blockPool.GetBlock(rightPlayer.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
                    rightPreviewArea.UpdateNextBlock(rightPlayer.nextBlock);
                }
            }
        }

        // 检查游戏是否完全结束
        if (leftPlayer.gameOver && rightPlayer.gameOver) {
            // 比较分数
            TCHAR resultText[64];
            if (leftScoreManager.GetScore() > rightScoreManager.GetScore()) {
                _stprintf_s(resultText, _T("左方获胜! %d vs %d"),
                    leftScoreManager.GetScore(), rightScoreManager.GetScore());
            }
            else if (rightScoreManager.GetScore() > leftScoreManager.GetScore()) {
                _stprintf_s(resultText, _T("右方获胜! %d vs %d"),
                    rightScoreManager.GetScore(), leftScoreManager.GetScore());
            }
            else {
                _stprintf_s(resultText, _T("平局! %d vs %d"),
                    leftScoreManager.GetScore(), rightScoreManager.GetScore());
            }

            settextstyle(40, 0, _T("黑体"));
            settextcolor(GREEN);
            outtextxy(TWO_PLAYER_SCREEN_WIDTH / 2 - 150, SCREEN_HEIGHT / 2 + 50, resultText);
            FlushBatchDraw();

            Sleep(3000);
            break;
        }

        // 根据等级调整下落速度(取两者中较高的等级)
        int higherLevel = max(leftScoreManager.GetLevel(), rightScoreManager.GetLevel());
        int delay = 150 - (higherLevel - 1) * 20;
        if (delay < 50) delay = 50;
        Sleep(delay);
    }
}

// ======================
// 自动展示模式实现（瞬间固定到目标位置）
// ======================
inline void RunAutoDemoGameDirect() {
    // 初始化随机种子
    unsigned int seed = static_cast<unsigned>(time(nullptr));

    // 初始化方块池
    BlockPool blockPool;
    blockPool.Initialize(seed, 10000);

    // 创建双缓冲图像
    IMAGE bufferImg(SCREEN_WIDTH, SCREEN_HEIGHT);

    // 设置背景颜色为白色
    setbkcolor(WHITE);
    cleardevice();

    // 加载背景图片
    LoadBackground();

    // 初始化分数管理器
    ScoreManager scoreManager;

    // 绘制游戏区域
    GameArea gameArea(scoreManager);
    PreviewArea previewArea;

    // 初始化当前方块和下一个方块的索引
    int curBlockIndex = 0;
    int nextBlockIndex = 1;

    // 获取当前方块和下一个方块
    TetrisBlock currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 1);
    TetrisBlock nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
    previewArea.UpdateNextBlock(nextBlock);

    // 创建AI决策器
    AIDecisionMaker aiDecisionMaker(gameArea);

    // 游戏主循环
    while (true) {
        // 开始双缓冲绘制
        BeginBatchDraw();

        // 1. 清空缓冲图像并绘制背景
        cleardevice();
        LoadBackground();

        // 2. 绘制游戏区域
        gameArea.Draw();
        gameArea.DrawTitle(L"AI");
        // 3. 绘制当前方块
        currentBlock.Draw(MARGIN, MARGIN);

        // 4. 绘制预览框
        previewArea.Draw();

        // 5. 绘制分数和等级
        scoreManager.Draw();

        // 结束双缓冲绘制
        FlushBatchDraw();

        // 检查暂停键
        if (GetAsyncKeyState(VK_SPACE) & 0x8000) {
            MessageBox(nullptr, _T("游戏已暂停\n\n按确定继续游戏"), _T("暂停"), MB_OK);
            while (GetAsyncKeyState(VK_SPACE) & 0x8000) Sleep(100);
        }

        // 修改后的AI决策逻辑 - 直接设置到目标位置
        TargetState target = aiDecisionMaker.CalculateBestTarget(currentBlock);

        if (target.isValid) {
            // 直接设置方块到目标状态
            currentBlock.SetRotation(target.rotation);
            currentBlock.SetX(target.x);
            currentBlock.SetY(target.y);

            // 检查是否碰撞（确保位置合法）
            if (aiDecisionMaker.IsConflict(gameArea.GetGrid(),
                currentBlock.GetType(),
                currentBlock.GetRotation(),
                currentBlock.GetX(),
                currentBlock.GetY())) {
                // 如果冲突则回退到初始位置
                currentBlock.SetX(WIDTH / 2 - 2);
                currentBlock.SetY(0);
                currentBlock.SetRotation(0);
                std::cout << "警告：目标位置冲突，已重置方块" << std::endl;
            }
        }
        
        if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
            settextstyle(40, 0, _T("黑体"));
            settextcolor(RED);
            outtextxy(SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("游戏结束!"));
            FlushBatchDraw();
            Sleep(2000);
            break;
        }
        // 方块自动下落逻辑（保持不变）
        if (gameArea.CanMoveDown(currentBlock)) {
            currentBlock.MoveDown();
        }
        else {
            // 固定当前方块
            gameArea.FixBlock(currentBlock);


            // 更新索引
            curBlockIndex = nextBlockIndex;
            nextBlockIndex += 1;

            // 检查游戏结束
            if (!gameArea.CanMoveDown(currentBlock) && currentBlock.GetY() == 0) {
                settextstyle(40, 0, _T("黑体"));
                settextcolor(RED);
                outtextxy(SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("游戏结束!"));
                FlushBatchDraw();
                Sleep(2000);
                break;
            }

            // 获取新方块
            currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 1);
            nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
            previewArea.UpdateNextBlock(nextBlock);
        }

        Sleep(200);
    }
}

// ======================
// 自动展示模式实现（逐步移到最后位置）
// ======================
inline void RunAutoDemoGameStepByStep() {
    // 初始化随机种子
    unsigned int seed = static_cast<unsigned>(time(nullptr));

    // 初始化方块池
    BlockPool blockPool;
    blockPool.Initialize(seed, 1000);

    // 创建图形窗口
    initgraph(SCREEN_WIDTH, SCREEN_HEIGHT);
    setbkcolor(WHITE);
    cleardevice();

    // 加载背景
    LoadBackground();

    // 初始化游戏组件
    ScoreManager scoreManager;
    GameArea gameArea(scoreManager);
    PreviewArea previewArea;

    // 初始化方块
    int curBlockIndex = 0;
    int nextBlockIndex = 1;
    TetrisBlock currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 1);
    TetrisBlock nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
    previewArea.UpdateNextBlock(nextBlock);

    // 创建AI决策器
    AIDecisionMaker aiDecisionMaker(gameArea);

    // 游戏主循环
    while (true) {
        // 计算最佳目标位置
        TargetState target = aiDecisionMaker.CalculateBestTarget(currentBlock);

        // 生成完整路径（包含精确下落步数）
        std::vector<AIDecision> path = aiDecisionMaker.CalculatePath(
            currentBlock, target, gameArea.GetGrid()
        );

        // 执行全部指令
        for (const auto& action : path) {
            // 执行动作
            switch (action) {
            case AIDecision::MOVE_LEFT:  currentBlock.MoveLeft();  break;
            case AIDecision::MOVE_RIGHT: currentBlock.MoveRight(); break;
            case AIDecision::ROTATE:     currentBlock.Rotate();    break;
            case AIDecision::DROP:       currentBlock.MoveDown();  break;
            }

            // 实时绘制
            BeginBatchDraw();
            cleardevice();
            LoadBackground();
            gameArea.Draw();
            gameArea.DrawTitle(L"AI DEMO");
            currentBlock.Draw(MARGIN, MARGIN);
            previewArea.Draw();
            scoreManager.Draw();
            FlushBatchDraw();

            // === 暂停处理 ===
            if (GetAsyncKeyState(VK_SPACE) & 0x8000) {
                MessageBox(nullptr, _T("游戏已暂停\n\n按确定继续游戏"), _T("暂停"), MB_OK);
                while (GetAsyncKeyState(VK_SPACE) & 0x8000) Sleep(100);
            }

            // 提前结束
            if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) {
                goto FORCED_STOP_IN_RunAutoDemoGameStepByStep;
            }

            // 控制速度（每步100ms）
            Sleep(10);
        }

        // 固定当前方块
        gameArea.FixBlock(currentBlock);

        // 游戏结束检测
        if (currentBlock.GetY() <= 0) {
        FORCED_STOP_IN_RunAutoDemoGameStepByStep:
            settextstyle(40, 0, _T("黑体"));
            settextcolor(RED);
            outtextxy(SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("游戏结束!"));
            FlushBatchDraw();
            Sleep(2000);
            break;
        }

        // 生成新方块
        curBlockIndex = nextBlockIndex;
        nextBlockIndex++;
        currentBlock = blockPool.GetBlock(curBlockIndex, WIDTH / 2 - 2, 1);
        nextBlock = blockPool.GetBlock(nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
        previewArea.UpdateNextBlock(nextBlock);
    }

}

// ======================
// 人机对战模式实现（AI逐步移到最后位置）
// ======================
inline void RunPlayerVsAIGame() {
    // 初始化随机种子
    unsigned int seed = static_cast<unsigned>(time(nullptr));

    // 初始化方块池
    BlockPool blockPool;
    blockPool.Initialize(seed, 1000);

    // 初始化图形窗口(双倍宽度)
    initgraph(TWO_PLAYER_SCREEN_WIDTH, SCREEN_HEIGHT);
    setbkcolor(WHITE);
    cleardevice();

    // 加载并拉伸背景图片
    IMAGE background;
    loadimage(&background, _T("./resources/background.jpg"), TWO_PLAYER_SCREEN_WIDTH, SCREEN_HEIGHT, true);
    putimage(0, 0, &background);

    // 初始化分数管理器
    ScoreManager playerScoreManager;
    ScoreManager aiScoreManager(RIGHT_GAME_OFFSET_X + GAME_AREA_WIDTH + MARGIN * 2,
        MARGIN + PREVIEW_HEIGHT * CELL_SIZE + MARGIN);

    // 初始化游戏区域
    GameArea playerGameArea(playerScoreManager);
    GameArea aiGameArea(aiScoreManager);

    // 初始化预览区域
    PreviewArea playerPreviewArea;
    PreviewArea aiPreviewArea(RIGHT_GAME_OFFSET_X + GAME_AREA_WIDTH + MARGIN * 2, MARGIN);

    // 初始化AI决策器
    AIDecisionMaker aiDecisionMaker(aiGameArea);

    // 初始化游戏状态
    struct GameState {
        bool gameOver = false;
        int blockIndex = 0;
        int nextBlockIndex = 1;
        TetrisBlock currentBlock;
        TetrisBlock nextBlock;
        std::vector<AIDecision> actionList; // AI指令列表
        size_t currentActionIndex = 0;     // 当前执行到第几个指令
    };

    GameState player, ai;

    // 初始化方块
    auto InitBlocks = [&]() {
        player.currentBlock = blockPool.GetBlock(player.blockIndex, WIDTH / 2 - 2, 0);
        player.nextBlock = blockPool.GetBlock(player.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
        playerPreviewArea.UpdateNextBlock(player.nextBlock);

        ai.currentBlock = blockPool.GetBlock(ai.blockIndex, WIDTH / 2 - 2, 0);
        ai.nextBlock = blockPool.GetBlock(ai.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
        aiPreviewArea.UpdateNextBlock(ai.nextBlock);

        // AI初始路径规划
        TargetState aiTarget = aiDecisionMaker.CalculateBestTarget(ai.currentBlock);
        ai.actionList = aiDecisionMaker.CalculatePath(ai.currentBlock, aiTarget, aiGameArea.GetGrid());
        ai.currentActionIndex = 0;
        };
    InitBlocks();

    // 游戏主循环
    while (true) {
        // === 绘制逻辑 ===
        BeginBatchDraw();
        cleardevice();
        putimage(0, 0, &background);

        // 绘制玩家区域
        playerGameArea.Draw(MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        playerGameArea.DrawTitle(L"Player", MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        if (!player.gameOver) {
            player.currentBlock.Draw(MARGIN + LEFT_GAME_OFFSET_X, MARGIN);
        }
        playerPreviewArea.Draw();
        playerScoreManager.Draw();

        // 绘制AI区域
        aiGameArea.Draw(MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        aiGameArea.DrawTitle(L"AI", MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        if (!ai.gameOver) {
            ai.currentBlock.Draw(MARGIN + RIGHT_GAME_OFFSET_X, MARGIN);
        }
        aiPreviewArea.Draw();
        aiScoreManager.Draw();

        FlushBatchDraw();

        // === 暂停处理 ===
        if (GetAsyncKeyState(VK_SPACE) & 0x8000) {
            MessageBox(nullptr, _T("游戏已暂停\n\n按确定继续游戏"), _T("暂停"), MB_OK);
            while (GetAsyncKeyState(VK_SPACE) & 0x8000) Sleep(100);
        }

        // === 玩家逻辑 ===
        if (!player.gameOver) {
            // 左移 (A键或左箭头)
            if ((GetAsyncKeyState('A') & 0x8000) || (GetAsyncKeyState(VK_LEFT) & 0x8000)) {
                if (playerGameArea.CanMoveLeft(player.currentBlock)) {
                    player.currentBlock.MoveLeft();
                }
            }
            // 右移 (D键或右箭头)
            if ((GetAsyncKeyState('D') & 0x8000) || (GetAsyncKeyState(VK_RIGHT) & 0x8000)) {
                if (playerGameArea.CanMoveRight(player.currentBlock)) {
                    player.currentBlock.MoveRight();
                }
            }
            // 下移 (S键或下箭头) 
            if ((GetAsyncKeyState('S') & 0x8000) || (GetAsyncKeyState(VK_DOWN) & 0x8000)) {
                if (playerGameArea.CanMoveDown(player.currentBlock)) {
                    player.currentBlock.MoveDown();
                }
            }
            // 旋转 (W键或上箭头)
            if ((GetAsyncKeyState('W') & 0x8000) || (GetAsyncKeyState(VK_UP) & 0x8000)) {
                if (playerGameArea.CanRotate(player.currentBlock)) {
                    player.currentBlock.Rotate();
                }
            }

            // 玩家方块自动下落
            if (playerGameArea.CanMoveDown(player.currentBlock)) {
                player.currentBlock.MoveDown();
            }
            else {
                playerGameArea.FixBlock(player.currentBlock);

                // 更新玩家方块
                player.blockIndex = player.nextBlockIndex;
                player.nextBlockIndex++;
                player.currentBlock = blockPool.GetBlock(player.blockIndex, WIDTH / 2 - 2, 0);
                player.nextBlock = blockPool.GetBlock(player.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
                playerPreviewArea.UpdateNextBlock(player.nextBlock);

                // 检查游戏结束
                if (!playerGameArea.CanMoveDown(player.currentBlock) && player.currentBlock.GetY() == 0) {
                    player.gameOver = true;
                }
            }
        }

        // === AI逻辑 ===
        if (!ai.gameOver) {
            if (ai.currentActionIndex < ai.actionList.size()) {
                // 执行当前指令（允许穿模）
                AIDecision action = ai.actionList[ai.currentActionIndex++];
                switch (action) {
                case AIDecision::MOVE_LEFT:  ai.currentBlock.MoveLeft();  break;
                case AIDecision::MOVE_RIGHT: ai.currentBlock.MoveRight(); break;
                case AIDecision::ROTATE:     ai.currentBlock.Rotate();    break;
                case AIDecision::DROP:       ai.currentBlock.MoveDown();  break;
                }
            }
            else {
                // 固定AI方块
                aiGameArea.FixBlock(ai.currentBlock);

                // 更新AI方块
                ai.blockIndex = ai.nextBlockIndex;
                ai.nextBlockIndex++;
                ai.currentBlock = blockPool.GetBlock(ai.blockIndex, WIDTH / 2 - 2, 0);
                ai.nextBlock = blockPool.GetBlock(ai.nextBlockIndex, PREVIEW_WIDTH / 2, PREVIEW_HEIGHT / 2);
                aiPreviewArea.UpdateNextBlock(ai.nextBlock);

                // 重新规划路径
                TargetState aiTarget = aiDecisionMaker.CalculateBestTarget(ai.currentBlock);
                ai.actionList = aiDecisionMaker.CalculatePath(ai.currentBlock, aiTarget, aiGameArea.GetGrid());
                ai.currentActionIndex = 0;

                // 检查游戏结束
                if (!aiGameArea.CanMoveDown(ai.currentBlock) && ai.currentBlock.GetY() == 0) {
                    ai.gameOver = true;
                }
            }
        }

        // === 游戏结束检查 ===
        if (player.gameOver || ai.gameOver) {
            // 显示结果
            settextstyle(40, 0, _T("黑体"));
            if (player.gameOver && ai.gameOver) {
                settextcolor(YELLOW);
                outtextxy(TWO_PLAYER_SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("双败结束!"));
            }
            else if (player.gameOver) {
                settextcolor(RED);
                outtextxy(LEFT_GAME_OFFSET_X + SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("玩家失败!"));
            }
            else {
                settextcolor(RED);
                outtextxy(RIGHT_GAME_OFFSET_X + SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 2, _T("AI失败!"));
            }
            FlushBatchDraw();
            Sleep(3000);
            break;
        }

        // === 速度控制 ===
        Sleep(140); // 固定帧率
    }

}
